import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Tabs, Tag } from 'tdesign-react';
import './index.module.less';
import { addTag, removeTag } from 'modules/layout/tags';
import { useLocation, useNavigate } from 'react-router-dom';

const { TabPanel } = Tabs;
const Tags: React.FC = () => {
  const dispatch = useDispatch();
  const location = useLocation();
  const navigate = useNavigate();
  const panels = useSelector((state: any) => state.tags.tags);
  const [value, setValue] = useState(location.pathname || '/user/index');
  const handleRemoveTag = (tag: any) => {
    if (panels.length === 1 || tag.value == '/user/index') return;
    dispatch(removeTag({ path: tag.value }));
    setValue(panels[tag.index - 1].path);
    navigate(panels[tag.index - 1].path);
  };
  useEffect(() => {
    setValue(location.pathname);
    localStorage.setItem('tags', JSON.stringify({ tags: panels, value }));
  }, [location.pathname]);
  const handleChangeTag = (path: string) => {
    navigate(path);
  };
  return (
    <div>
      <div className='tag-container'>
        <Tabs placement={'top'} size={'medium'} theme={'card'} value={value} onRemove={handleRemoveTag}>
          {panels.map(({ path, label }: { path: string; label: string }, index: number) => (
            <TabPanel
              key={path}
              value={path}
              onClick={() => handleChangeTag(path)}
              label={label}
              removable={true}
            ></TabPanel>
          ))}
        </Tabs>
      </div>
    </div>
  );
};

export default Tags;
